/*
 * @lc app=leetcode.cn id=653 lang=cpp
 *
 * [653] 两数之和 IV - 输入 BST
 */
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>

using namespace std;
// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    vector<int> arr;
public:
    void inOrder(TreeNode* root) {
        if(!root) {
            return ;
        }
        inOrder(root->left);
        arr.push_back(root->val);
        inOrder(root->right);
        
    }
    bool findTarget(TreeNode* root, int k) {
        inOrder(root);
        int n = arr.size();
        // for(int i = 0;i < n-1;i++) {
        //     for(int j = i+1;j < n;j++) {
        //         if(arr[i] + arr[j] == k) {
        //             return true;
        //         }
        //     }
        // }

        //有序数组的查找两数之和可以使用双指针，而非双重循环以降低复杂度
        int left = 0, right = n - 1;
        while (left < right) {
            if (arr[left] + arr[right] == k) {
                return true;
            }
            if (arr[left] + arr[right] < k) {
                left++;
            } else {
                right--;
            }
        }
        return false;
    }
};
// @lc code=end

